package org.osami.commons.smarthome.programnotifier;

import java.util.Dictionary;
import java.util.Hashtable;

import org.osami.commons.smarthome.settopbox.ISetTopBoxComponent;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;

public class UserAnswerHandler implements EventHandler {

	Hashtable<Integer, ProgramInfo> questions = new Hashtable();
	private static UserAnswerHandler inst = null;
	
	public static UserAnswerHandler instance() {
		//if (null == inst)
			inst = new UserAnswerHandler();
		
		return inst;
	}
	
	private UserAnswerHandler() {
		System.out.println("UserAnswerHandler: registering service");
		ServiceRegistration aha = Activator.getBundleContext().registerService(EventHandler.class.getName(), this, getHandlerServiceProperties("org/osami/commons/dialog/UserAnswer"));
		System.out.println("UserAnswerHandler: registering service "+aha.toString() );
	}
	
	void registerQuestion(int id, ProgramInfo info) {
		System.out.println("UserAnswerHandler: registering question " + id);
		questions.put(new Integer(id), info);
	}
	
	@Override
	public void handleEvent(Event event) {
		//System.out.println("UserAnswerHandler: Handling event");
		System.out.println("UserAnswerHandler: propertynames: "+event.getPropertyNames().toString());
		Integer id = new Integer((String)event.getProperty("questionId"));
		System.out.println("UserAnswerHandler: handling answer with id " + id);
		ProgramInfo info = questions.get(id);
		questions.remove(id); // Forget other answers, only the first answer is handled
		
		// TODO: READ ANSWER
		
		int answer = Integer.parseInt(((String)event.getProperty("answerId")).replace(";", ""));
		
		if (0 == answer) {
			
			if (null == info) {
				System.out.println("UserAnswerHandler: Could not associate answer with any program");
			} else {
				System.out.println("UserAnswerHandler: Program match, finding service to handle recording...");
				ServiceReference ref = Activator.getBundleContext().getServiceReference(ISetTopBoxComponent.class.getName());
				if (null == ref) {
					System.out.println("UserAnswerHandler: SetTopBox service not found");
				} else {
					System.out.println("UserAnswerHandler: SetTopBox service found, scheduling record");
					ISetTopBoxComponent comp = (ISetTopBoxComponent)Activator.getBundleContext().getService(ref);
					comp.scheduleEventRecord(info.getId(), info.getServiceReference());
				}
			}
			
		} else {
			System.out.println("UserAnswerHandler: User rejected recording proposal, doing nothing");
		}
	}
	
	protected Dictionary getHandlerServiceProperties(String... topics) {  
        Dictionary result = new Hashtable();  
        result.put(EventConstants.EVENT_TOPIC, topics);  
        return result;  
}
	
}
